package com.dang.alex.servlet.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dang.alex.model.Book;
import com.dang.alex.model.Category;
import com.dang.alex.model.Product;
import com.dang.alex.model.User;
import com.dang.alex.service.ProductService;
import com.dang.alex.service.UserService;
import com.dang.alex.service.imp.ServiceDAOFactory;
import com.dang.alex.util.Md5Code;

@WebServlet("/user/Login.do")
public class LoginServlet extends HttpServlet {
	public static final String METHOD_TOLOGIN = "0";
	public static final String METHOD_LOGIN = "1";
	public static final long serialVersionUID=7845020365782809722L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method=req.getParameter("method");
		if(method!=null) {
			switch(method) {
			case LoginServlet.METHOD_TOLOGIN:
				req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
				break;
			case LoginServlet.METHOD_LOGIN:
				try {
					login(req,resp);
				}catch(Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		}
	}
	private void login(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		UserService userService=ServiceDAOFactory.getUserDAO();
		User user=userService.findByEmail(req.getParameter("email"));
		if(user==null||!user.getPassword().equals(Md5Code.createMd5Code(req.getParameter("password")))) {
			req.setAttribute("login_err", "用户密码错误");
			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
			return ;
		}
		user.setLastLoginIp(req.getRemoteAddr());
		user.setLastLoginTime(System.currentTimeMillis());
		userService.update(user);
		req.getSession().setAttribute("s_user", user);
		if(!user.isEmailVerify()) {
			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
		}
		Map<String, List>datas=new HashMap<String, List>();
		initCategory(datas);
		initRecommend(datas);
		initHotBooks(datas);
		initNewBooks(datas);
		req.setAttribute("datas", datas);
		req.getRequestDispatcher("/WEB-INF/view/home/main.jsp").forward(req, resp);
	}
	private void initRecommend(Map<String, List> datas) {
		List<Book> books=new ArrayList<Book>();
		ProductService productService=ServiceDAOFactory.getProductService();
		try {
			books.add((Book)productService.findById((int)(Math.random()*20+1)));
			books.add((Book)productService.findById((int)(Math.random()*20+1)));
			datas.put("books", books);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void productDetail(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		Book book=null;
		try {
			String id=req.getParameter("id");
			if(id!=null) {
				book=(Book)ServiceDAOFactory.getProductService().findById(new Integer(id));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		req.setAttribute("book", book);
		req.getRequestDispatcher("/WEB-INF/view/home/product.jsp").forward(req, resp);
	}
	private void initNewBooks(Map<String,List> datas) {
		List<Book>books=new ArrayList<Book>();
		try {
			for(Product p:ServiceDAOFactory.getProductService().findByNew(4)) {
				books.add((Book)p);
			}
			datas.put("newBooks", books);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	private void initHotBooks(Map<String,List> datas) {
		List<Book> books=new ArrayList<Book>();
		List<Product> pros;
		try {
			pros=ServiceDAOFactory.getProductService().findByHot(4);
			for(Product p:pros) {
				books.add((Book)p);
			}
			datas.put("hotBooks", books);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	private void initCategory(Map<String,List> datas) {
		List<Category> cats;
		try {
			List<Category>list=ServiceDAOFactory.getCategoryService().findAll();
			cats=findByParentId(list,1);
			for(Category c: cats) {
				c.setSubCats(findByParentId(list,c.getId()));
			}
			datas.put("category", cats);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	private List<Category> findByParentId(List<Category> list,int id){
		List<Category>subCats=new ArrayList<Category>();
		for(Category c: list) {
			if(c.getParentId()==id) {
				subCats.add(c);
			}
		}
		return subCats;
	}
}
